<template>
	<view class="page">
		<view class="h30"></view>
		<view class="flex-SB" style="width: 720rpx;margin: 0 auto;">
			<view class="tabs">
				<view class="tabs-item" v-for="(item,idx) in utabs" @click="tabChange(idx)"
					:class="{activeItem:idx==dayActive}">{{item.name}}</view>
			</view>
			<view style="width: 220rpx;position: relative;z-index: 99999;">
				<view class="emo-type">
					<view @click="emoClick()" class="emo-type-item">{{emoTypeStr}}指数</view>
					<view v-show="emoTypeShow">
						<view v-for="(item,idx) in emoTypes" @click="emoChange(idx)" class="emo-type-item" v-show="emoActive!=idx">{{item.name}}指数
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="h30"></view>
		<view v-if="checkType=='today'" @click="showDayModal()"  class="date-select">
			<u-icon bold color="#1D6EFA" size="14" name="arrow-left"></u-icon>
			<view style="margin: 0 12rpx;">{{choiceDay}}</view>
			<u-icon bold color="#1D6EFA" size="14" name="arrow-right"></u-icon>
		</view>
		<view v-if="checkType=='week'"  class="date-select">
			<u-icon bold @click="checkWeek('pre')" color="#1D6EFA" size="14" name="arrow-left"></u-icon>
			<view style="margin: 0 12rpx;">{{choiceWeek.weekStr}}</view>
			<u-icon bold @click="checkWeek('next')" color="#1D6EFA" size="14" name="arrow-right"></u-icon>
		</view>
		<view  v-if="checkType=='month'" class="date-select">
			<u-icon bold @click="checkMonth('pre')" color="#1D6EFA" size="14" name="arrow-left"></u-icon>
			<view style="margin: 0 12rpx;">{{choiceMonth.year+'-'+choiceMonth.month}}</view>
			<u-icon bold @click="checkMonth('next')" color="#1D6EFA" size="14" name="arrow-right"></u-icon>
		</view>
		<view class="h30"></view>
		<!-- 切换日 -->
		<block v-if="checkType=='today'">
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}占比</view>
				
				<image v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;" src="https://baxztech.com/bian_admin_api/public/bianmp/pieEmpty.png"></image>
				<l-echart v-else style="width: 300px;height: 230px;margin: 0 auto;" ref="emoChartPie"></l-echart>
				<view style="color: #7D8592;">{{dayContent}}</view>
			</view>
			<view class="h30"></view>
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}状况</view>
				<view v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;text-align: center;line-height: 450rpx;color: #777777;" >
					-暂无数据-
				</view>
				<l-echart v-else style="width: 300px;height: 230px;margin: 0 auto;" ref="emoChartBar"></l-echart>
			</view>
			<view class="block marginT30" v-show="indexType=='emotion'&&!isEmpty">
						<view style="color: #333333;font-size: 28rpx;">情绪词云</view>
							<l-echart style="width: 300px;height: 230px;margin: 0 auto;" ref="chartRef"></l-echart>
						<view class="h30"></view>
						<view class="h30"></view>
						<view class="flex-SB">
							<view style="width: 50%;display: flex;flex-direction: column;align-items: center;">
								<view style="font-size: 20rpx;color: #777;">{{emoTypeStr}}最好时段</view>
								<view style="font-size: 32rpx;color: #FF8D1A;">{{bestEmoStr}}</view>
							</view>
							<view style="width: 50%;">
								<view style="display: flex;flex-direction: column;align-items: center;">
									<view style="font-size: 20rpx;color: #777;">{{emoTypeStr}}最差时段</view>
									<view style="font-size: 32rpx;color: #2F3033;">{{badEmoStr}}</view>
								</view>
							</view>
						</view>
					</view>
		</block>
		<!-- 切换周 -->
		<block v-if="checkType=='week'">
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}状况</view>
				<view v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;text-align: center;line-height: 450rpx;color: #777777;" >
					-暂无数据-
				</view>
				<view v-else style="min-height: 230px;">
					<l-echart style="width: 300px;height: 230px;margin: 0 auto;min-height: 230px;" ref="emoChartLine"></l-echart>
				</view>
			</view>
			<view class="block marginT30" v-show="!isEmpty">
				<view style="color: #333333;font-size: 30rpx;font-weight: 500;">本周趋势</view>
				<view class="h30"></view>
				<view style="color: #7D8592;font-size: 28rpx;line-height: 46rpx;">
					{{weekContent}}
				</view>
			</view>
			<view class="block marginT30" v-show="!isEmpty">
				<view style="color: #333333;font-size: 28rpx;">推荐</view>
				<view class="h30"></view>
				<view class="flex-SB" style="padding: 0 10rpx;">
					<view style="display: flex;" @click="$navigateTo('/pagesA/pages/list/train')">
						<view>
							<view class="b-title">尝试一次冥想</view>
							<view class="b-btn">去冥想</view>
						</view>
						<image mode="aspectFill" class="b-image" src="https://baxztech.com/bian_admin_api/public/bianmp/mignxIcon.png"></image>
					</view>
					<view style="display: flex;" @click="$navigateTo('/pagesA/pages/list/train')">
						<view>
							<view class="b-title">尝试一次问卷</view>
							<view class="b-btn">去填写</view>
						</view>
						<image class="b-image" src="https://baxztech.com/bian_admin_api/public/bianmp/wenjIcon.png"></image>
					</view>
				</view>
			</view>
		</block>
		<!-- 切换月 -->
		<block v-if="checkType=='month'">
			<view class="h30"></view>
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}时段</view>
				<view class="h30"></view>
				<view v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;text-align: center;line-height: 450rpx;color: #777777;" >
					-暂无数据-
				</view>
				<!-- <l-echart v-else style="width: 300px;height: 230px;margin: 0 auto;" ref="emoChartMonth"></l-echart> -->
				<view class="flex-SB">
					<view class="emoTimeItem">
						<view style="width:15px;height:15px;" v-for="item in [1,5,10,15,20,25,30]">
							{{item}}
						</view>
					</view>
					<view style="width: 325px;min-height: 198px;">
						<view style="display:flex;justify-content: space-between;font-size: 9px;color: #AAA;width: 315px;margin-bottom: 5px;margin-left: 5px;">
							<view v-for="item in [0,3,6,9,12,15,18,21,23]">
								<view>{{item}}</view>
							</view>
						</view>
						<view  class="litteA" v-for="item in month">
							<view v-show="item.hourData.length>0" v-for="items in item.hourData" :style="{background: getClass(items)}" class="litteB"></view>
							<view v-show="item.hourData.length==0" v-for="items in 24"  class="litteB"></view>
						</view>
					</view>
				</view>
				<view class="h30"></view>
				<view class="m-box">
					<view class="m-b-item">
						<view class="mb-title">{{emoTypeStr}}指数</view>
						<view class="mb-content">{{monthHourMean.mean}}</view>
					</view>
					<view class="m-b-item">
						<view class="mb-title">本月均值</view>
						<view class="mb-content">{{monthHourMean.mean}}</view>
					</view>
					<view class="m-b-item">
						<view class="mb-title">{{monthStrObj[indexType][0]}}</view>
						<view class="mb-content">{{monthContents[2]||'0'}}</view>
					</view>
				</view>
				<view class="m-box">
					<view class="m-b-item">
						<view class="mb-title">较上月</view>
						<view class="mb-content">{{monthHourMean.diff}}</view>
					</view>
					<view class="m-b-item">
						<view class="mb-title">上月均值</view>
						<view class="mb-content">{{monthHourMean.premean}}</view>
					</view>
					<view class="m-b-item">
						<view class="mb-title">{{monthStrObj[indexType][1]}}</view>
						<view class="mb-content">{{monthContents[1]||'0'}}</view>
					</view>
				</view>
			</view>
			<view class="h30"></view>
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}占比</view>
				
				<image v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;" src="https://baxztech.com/bian_admin_api/public/bianmp/pieEmpty.png"></image>
				<view v-else style="display: flex;align-items: center;">
					<view class="pie-box">
						<view class="pie-title">本月情绪主题</view>
						<view class="pie-content">本月情绪主题为{{monthContents[0]||''}}</view>
					</view>
					<view style="width: 160px;height: 160px;margin: 0 auto;" >
						<l-echart style="width: 160px;height: 160px;margin: 0 auto;" ref="emoChartPieMonth"></l-echart>
					</view>
					<view>
						<view class="pie-box">
							<view class="pie-title">{{monthStrObj[indexType][0]}}天数</view>
							<view class="pie-content">本月{{monthStrObj[indexType][0]}}天数为{{monthContents[2]||'0'}}天</view>
						</view>
						<view class="pie-box">
							<view class="pie-title">{{monthStrObj[indexType][1]}}天数</view>
							<view class="pie-content">本月{{monthStrObj[indexType][1]}}天数为{{monthContents[1]||'0'}}天</view>
						</view>
					</view>
				</view>
				<view style="color: #7D8592;"></view>
			</view>
			<view class="h30"></view>
			<view class="block">
				<view style="color: #333333;font-size: 28rpx;">{{emoTypeStr}}状况</view>
				<view v-if="isEmpty" style="width: 686rpx;height: 450rpx;margin: 60rpx auto 0;text-align: center;line-height: 450rpx;color: #777777;" >
					-暂无数据-
				</view>
				<view v-else style="width: 300px;height: 280px;margin: 0 auto;">
					<l-echart style="width: 300px;height: 280px;margin: 0 auto;" ref="emoChartBar"></l-echart>
				</view>
			</view>
		</block>
<!-- 		<view class="h30"></view>
		<view class="block"
			style="height: 364rpx;background: linear-gradient(180deg, #ffffff 100%, #e3f9ff 0%);box-shadow: 4rpx 8rpx 16rpx #a4aede2e;">
		</view> -->
		<view class="data-day-modal" v-show="dayModal" @click="closeDayModal">
			<view class="data-day">
				<!-- <img src="https://baxztech.com/bian_admin_api/public/bianmp/welcome-close.png" alt="" class="close" @click="closeDayModal"> -->
				<view style="display: flex;justify-content: center;">
					<u-icon name="close" class="close" @click="closeDayModal" color="#2979ff" size="28"></u-icon>
				</view>

				<view class="day-month" v-for="(item,index ) in allMonthData" :key="index">
					<view class="month-title">{{item.year+'-'+item.month}}</view>
					<view class="day-list">
						<view class="day-box" v-for="(t,i) in item.days" :key="i">
							<button :class="t.has==0 ? 'day':'day-ac'" :disabled="t.has==0"
								@click="checkDay(t.time)">{{t.day}}</button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="h30"></view>
	</view>
</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	import registerWordcloud from '@/uni_modules/lime-echart-wordcloud'
	import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
	import {toTotalArr,maxsequence,initReport,toDiff} from "@/config/util.js"
	import {
		mapState,
		mapGetters
	} from 'vuex'
	registerWordcloud(echarts);

	export default {
		computed: {
			...mapState(['member']),
		},
		data() {
			return {
				monthHourMean:{
					mean:'',
					premean:'',
					diff:''
				},
				monthStrObj:{
					emotion:['心情差','心情好'],
					tired:['感到轻松','觉得疲惫'],
					stress:['压力大','放松']
				},
				daybardata:{
					emotion:[],
					tired:[],
					stress:[],
					time:[]
				},
				monthContents:['','',''],
				dayContent:'',
				weekContent:'',
				bestEmoStr:'-',
				badEmoStr:'-',
				choiceDay: '-',
				choiceDayTime: '',
				dayActive: 0,
				emoActive: 0,
				todayPercentAll: {},
				indexType: 'emotion',
				emoTypeShow: false,
				dayModal:false,
				checkType: 'today',
				utabs: [{
						name: '日',
						field:'today'
					},
					{
						name: '周',
						field:'week'
					},
					{
						name: '月',
						field:'month'
					}
				],
				emoTypeStr: '心情',
				today: [],
				preday: [],
				dayMean: {
					emotion: '',
					tired: '',
					stress: ''
				},
				predayMean: {
					emotion: '',
					tired: '',
					stress: ''
				},
				dayPercent: {},
				weekHourData:{},
				weekTimeLine:[],
				percentageChartDomDay: '',
				allWeekList: [],
				choiceWeek: '',
				choiceWeekNum: 12,
				week: [],
				preweek: [],
				weekMean: {},
				preweekMean: {},
				weekPercent: {},
				weekPercentAll: {},
				percentageChartDomWeek: '',
				allMonthList: [],
				choiceMonthNum: 3,
				choiceMonth: '',
				month: [],
				premonth: [],
				monthMean: {},
				premonthMean: {},
				monthPercent: {},
				monthPercentAll: {},
				allMonthData:[],
				emoStableStr:'',
				haswordCloud:false,
				isEmpty:true,
				contentStr:{
					emotion:'',
					tired:'',
					stress:''
				},
				emoTypes: [{
						name: '心情',
						tps:'emotion'
					},
					{
						name: '压力',
						tps:'stress'
					},
					{
						name: '精力',
						tps:'tired'
					}
				]
			};
		},
		onLoad() {
			let date = new Date()
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();
			this.choiceDay = year + '年' + month + '月' + day + '日';
			this.choiceDayTime = parseInt(date.getTime() / 1000);
			this.getRpData();
		},
		methods: {
			getClass(item){
				if(item[this.indexType] == null) return '';
				let colorList = ['#14b3f8', '#fcc856', '#ff4d31']
				if(this.indexType == 'stress'){
					colorList = colorList.reverse();
				}
				if(item[this.indexType] >69){
					return colorList[0];
				}else if(item[this.indexType] >49){
					return colorList[1];
				}else{
					return colorList[2];
				}
				return '';
			},
			initDayLineChart(rawData, timeLine){
				// console.log("-----------dayline");
				// console.log(this.indexType);
				// console.log(this.daybardata);
				// console.log(rawData);
				// console.log(timeLine);
				const totalData = [];
				for (let i = 0; i < rawData[0].length; ++i) {
					let sum = 0;
					for (let j = 0; j < rawData.length; ++j) {
						sum += rawData[j][i];
					}
					totalData.push(sum);
				}
				let colorList = [ "#FF4D31", "#FDC956","#3FE0AC"]
				if(this.indexType != 'stress'){
					colorList = colorList.reverse();
				}
				const series = rawData.map((name, sid) => {
					return {
						name,
						type: 'bar',
						stack: 'total',
						barMaxWidth: 7,
						emphasis: {
						        focus: 'series'
						      },
						itemStyle: {
							
							color: colorList[sid]
						},
						label: {
							position:'inside',
							fontSize:8,
							show: true,
							// formatter: (params) => Math.round(params.value * 100) + '--%',
							formatter: (params) => {
								if (params.value == 0) return '';
								return Math.round(params.value * 100) + '%'
							}
						},
						areaStyle: {},
						data: rawData[sid].map((d, did) => totalData[did] <= 0 ? null : d / totalData[did])
					};
				});
				let option = {
					grid: {
						nameTextStyle: {
							color: "#2F3033",
						},
					},
					xAxis: {
						type: "category",
						axisLabel: {
							color: "#2F3033"
						},
						data: timeLine
					},
					legend: {
						icon: 'circle',
						top: '0%',
						right: '0%',
						textStyle: {
							color: "#2F3033"
						}
					},
					yAxis: {
						type: "value",
						axisLabel: {
							formatter(value) {
								return value * 100 + '%';
							},
							color: "#2F3033"
						}
					},
					series: series
				}
				this.$nextTick(()=>{
					this.$refs.emoChartBar.init(echarts, chart => {
						chart.setOption(option);
					});
				})
			},
			initWeekLineChart(rawData, timeLine){
				// console.log("-------");
				// console.log(rawData);
				// console.log(timeLine);
				const totalData = [];
				for (let i = 0; i < rawData[0].length; ++i) {
					let sum = 0;
					for (let j = 0; j < rawData.length; ++j) {
						sum += rawData[j][i];
					}
					totalData.push(sum);
				}
				let colorList = [ "#FF4D31", "#FDC956","#3FE0AC"]
				if(this.indexType != 'stress'){
					colorList = colorList.reverse();
				}
				const series = rawData.map((name, sid) => {
					return {
						name,
						type: 'bar',
						stack: 'total',
						emphasis: {
						        focus: 'series'
						      },
						itemStyle: {
							color: colorList[sid]
						},
						label: {
							position:'inside',
							show: true,
							// formatter: (params) => Math.round(params.value * 100) + '--%',
							formatter: (params) => {
								if (params.value == 0) return '';
								return Math.round(params.value * 100) + '%'
							}
						},
						areaStyle: {},
						data: rawData[sid].map((d, did) => totalData[did] <= 0 ? null : d / totalData[did])
					};
				});
				let option = {
					grid: {
						nameTextStyle: {
							color: "#2F3033",
						},
					},
					xAxis: {
						type: "category",
						axisLabel: {
							color: "#2F3033"
						},
						data: timeLine
					},
					legend: {
						icon: 'circle',
						top: '0%',
						right: '0%',
						textStyle: {
							color: "#2F3033"
						}
					},
					yAxis: {
						type: "value",
						axisLabel: {
							formatter(value) {
								return value * 100 + '%';
							},
							color: "#2F3033"
						}
					},
					series: series
				}
				this.$nextTick(()=>{
					this.$refs.emoChartLine.init(echarts, chart => {
						chart.setOption(option);
					});
				})
			},
			checkMonth(type){
				if(type=='next'){
					let num = this.choiceMonthNum
					num = num + 1
					if (num > this.allMonthList.length - 1) {
						num = this.allMonthList.length - 1
						 return this.$toast('已到最后');
					}
					this.choiceMonthNum = num
					this.choiceMonth = this.allMonthList[this.choiceMonthNum]
					this.monthReport(this.member.phone, this.choiceMonth.startTime, this.choiceMonth.endTime, this.allMonthList[
						this.choiceMonthNum - 1].startTime, this.allMonthList[this.choiceMonthNum - 1].endTime)
				}
				if(type=='pre'){
					let num = this.choiceMonthNum
					num = num - 1
					if (num < 1) {
						num = 1
						return this.$toast('已到最前');
					}
					this.choiceMonthNum = num
					this.choiceMonth = this.allMonthList[this.choiceMonthNum]
					this.monthReport(this.member.phone, this.choiceMonth.startTime, this.choiceMonth.endTime, this.allMonthList[
						this.choiceMonthNum - 1].startTime, this.allMonthList[this.choiceMonthNum - 1].endTime)
				}
			},
			checkWeek(type){
				if(type=='next'){
					let num = this.choiceWeekNum
					num = num + 1
					if (num > this.allWeekList.length - 1) {
						num = this.allWeekList.length - 1
						return this.$toast('已到最后');
					}
					this.choiceWeekNum = num
					this.choiceWeek = this.allWeekList[this.choiceWeekNum]
					this.weekReport(this.member.phone, this.choiceWeek.startTime, this.choiceWeek.endTime, this.allWeekList[this
						.choiceWeekNum - 1].startTime, this.allWeekList[this.choiceWeekNum - 1].endTime)
				}
				if(type=='pre'){
					let num = this.choiceWeekNum
					num = num - 1
					if (num < 1) {
						num = 1
						return this.$toast('已到最前');
					}
					this.choiceWeekNum = num
					this.choiceWeek = this.allWeekList[this.choiceWeekNum]
					this.weekReport(this.member.phone, this.choiceWeek.startTime, this.choiceWeek.endTime, this.allWeekList[this
						.choiceWeekNum - 1].startTime, this.allWeekList[this.choiceWeekNum - 1].endTime)
				}
			},
			checkDay(time) {
				let date = new Date(time * 1000)
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				this.choiceDay = year + '年' + month + '月' + day + '日'
				this.choiceDayTime = time
				this.dayModal = false
				this.dayReport()
			},
			showDayModal() {
				if(this.allMonthData.length == 0) this.dataDay();
				this.dayModal = true
			},
			closeDayModal() {
				this.dayModal = false
			},

			emoClick() {
				if (this.emoTypeShow) {
					this.emoTypeShow = false;
				} else this.emoTypeShow = true;
			},
			//情绪指数切换
			emoChange(n) {
				 this.emoTypeShow = false;
				if(this.emoActive == n){
					return;
				}
				this.emoActive = n;
				this.emoTypeStr = this.emoTypes[n].name;
				this.indexType = this.emoTypes[n].tps;
				
				let data = this[this.checkType]
				let type = 'name';
				if(this.checkType == 'month'){
					type = 'date';
					this.percentageChartMonth(this.monthPercentAll.percentAll[this.indexType],this.monthPercentAll[this.indexType+'HourPie']);
					this.initChartBar(data,type)
				}
				
				if(this.checkType == 'week'){
					this.setWeekContent(this.weekHourData[this.indexType+'HourPie'],this.weekHourData.percentAll[this.indexType]);
					this.initWeekLineChart(this.weekHourData[this.indexType+'HourPie'].daylist,this.weekTimeLine)
				}
				if(this.checkType == 'today'){
					this.percentageChartDay(this[this.checkType+'PercentAll'][this.indexType]);
					this.setDayContent(this.today,this[this.checkType+'PercentAll'][this.indexType]);
					// this.initChartBar(data,type)
					
					this.initDayLineChart(this.daybardata[this.indexType],this.daybardata.time)
				}
			},
			//日周月切换
			tabChange(n) {
				if (this.dayActive == n) return;
				this.dayActive = n;
				this.checkType = this.utabs[n].field;
				this.getRpData();
			},
			getRpData() {
				if (this.dayActive == 0) {
					this.dayReport();
				}
				if (this.dayActive == 1) {
					this.dataWeek()
				}
				if (this.dayActive == 2) {
					this.dataMonth();
				}
			},
			contrastWeek() {
				let preMean = this.preweekMean[this.indexType]
				let todayMean = this.weekMean[this.indexType]
				let difEnd = null
				if (todayMean >= preMean) {
					let dif = (todayMean / preMean - 1) * 100
					difEnd = dif.toFixed(1)
				}
				if (todayMean < preMean) {
					let dif = (1 - todayMean / preMean) * 100
					difEnd = dif.toFixed(1)
				}
				return difEnd+'%';
			},
			dataWeek() {
				uni.$u.http.post('/client/data_week', {
					phone: this.member.phone
				}).then(res => {
					if (res.status == 200) {
						this.allWeekList = res.data.dateList
						this.choiceWeekNum = res.data.dateList.length - 1
						this.choiceWeek = res.data.dateList[this.choiceWeekNum]
						this.weekReport(this.member.phone, this.choiceWeek.startTime, this.choiceWeek.endTime, this
							.allWeekList[this.choiceWeekNum - 1].startTime, this.allWeekList[this
								.choiceWeekNum - 1].endTime)
					}
				});
			},
			dataMonth() {
				uni.$u.http.post('/client/data_month', {
					phone: this.member.phone,
				}).then(res => {
					if (res.status == 200) {
						this.allMonthList = res.data.allMonthData
						this.choiceMonthNum = res.data.allMonthData.length - 1
						this.choiceMonth = res.data.allMonthData[this.choiceMonthNum]
						this.monthReport(this.member.phone, this.choiceMonth.startTime, this.choiceMonth.endTime,
							this.allMonthList[this.choiceMonthNum - 1].startTime, this.allMonthList[this
								.choiceMonthNum - 1].endTime)
					}
				});
			},
			//月数据
			monthReport(phone, startTime, endTime, preStartTime, preEndTime) {
				uni.$u.http.post('/client/month_reports', {
					phone,
					startTime:startTime*1000,
					endTime:endTime*1000,
					preStartTime:preStartTime*1000,
					preEndTime:preEndTime*1000
				}).then(res => {
					if (res.status == 200) {
						this.month = res.data.month
						this.premonth = res.data.premonth
						if (res.data.month.length > 0) {
							this.isEmpty = false;
							let data = this[this.checkType]
							this.initChartBar(data,'date')
							this.monthPercentAll = initReport(res.data.month,res.data.premonth);
							// console.log(this.monthPercentAll.percentAll[this.indexType]);
							this.percentageChartMonth(this.monthPercentAll.percentAll[this.indexType],this.monthPercentAll[this.indexType+'HourPie']);
						}else{
							this.isEmpty = true;
						}
					}
				});
			},
			//周数据
			weekReport(phone, startTime, endTime, preStartTime, preEndTime) {
				uni.$u.http.post('/client/week_reports', {
					phone,
					startTime:startTime*1000,
					endTime:endTime*1000,
					preStartTime:preStartTime*1000,
					preEndTime:preEndTime*1000
				}).then(res => {
					if (res.status == 200) {
						if (res.data.dataLen > 0) {
							this.isEmpty = false;
							this.week = res.data.week
							this.preweek = res.data.preweek
							this.weekHourData = initReport(res.data.week,res.data.preweek)
							this.setWeekContent(this.weekHourData[this.indexType+'HourPie'],this.weekHourData.percentAll[this.indexType]);
							let data = this[this.checkType]
							let lineD = res.data.week;
							let timeLine = []
							let lnewarr = [
								[],
								[],
								[]
							];
							
							for(let i in lineD){
								let item = lineD[i]
								timeLine.push(item.date)
							}
							this.weekTimeLine = timeLine;
							this.initWeekLineChart(this.weekHourData[this.indexType+'HourPie'].daylist,this.weekTimeLine)
							// this.initWeekLineChart(emotionHourPie.daylist,['心情愉悦', '心情一般', '心情较差'],timeLine)
						}else{
							this.isEmpty = true;
						}
					}
				});
			},
			//日数据
			dayReport() {
				uni.$u.http.post('/client/day_report', {
					phone: this.member.phone,
					time: this.choiceDayTime
				}).then(res => {
					if (res.status == 200) {
						if(res.data.today.length<1){
							return this.isEmpty = true;
						}
						for(let i in res.data.today){
							if(res.data.today[i].tired!=null){
								res.data.today[i].tired = 100 - res.data.today[i].tired;
							}
						}
						
						this.today = res.data.today;
						
						this.isEmpty = false;
						this.preday = res.data.preday || []
						let initData = {hourData:[]};
						initData.hourData = res.data.today
						let initR = initReport([initData],[res.data.preday]);
						this.todayPercentAll = initR.percentAll;
						
						
						let hourList = res.data.today;
						let emotionData = [[],[],[]];
						let tiredData = [[],[],[]];
						let stressData = [[],[],[]];
						let barTime = [];
						for(let i in hourList){
							if(hourList[i].emotion){
								emotionData[0].push(hourList[i].emotions.up)
								emotionData[1].push(hourList[i].emotions.mid)
								emotionData[2].push(hourList[i].emotions.down)
							}else{
								emotionData[0].push(null)
								emotionData[1].push(null)
								emotionData[2].push(null)
							}
							
							if(hourList[i].tired){
								tiredData[0].push(hourList[i].tireds.up)
								tiredData[1].push(hourList[i].tireds.mid)
								tiredData[2].push(hourList[i].tireds.down)
							}else{
								tiredData[0].push(null)
								tiredData[1].push(null)
								tiredData[2].push(null)
							}
							if(hourList[i].stress){
								stressData[0].push(hourList[i].stresss.up)
								stressData[1].push(hourList[i].stresss.mid)
								stressData[2].push(hourList[i].stresss.down)
							}else{
								stressData[0].push(null)
								stressData[1].push(null)
								stressData[2].push(null)
							}
							barTime.push(hourList[i].hour)
						}
						this.daybardata.emotion = emotionData;
						this.daybardata.tired = tiredData;
						this.daybardata.stress = stressData;
						this.daybardata.time = barTime;
						// console.log(this.checkType);
						this.initDayLineChart(this.daybardata[this.indexType],this.daybardata.time)
						
						
						
						
						let emoType = ['emotion','stress','tired']
						for(let i in emoType){
							let piearr = [];
							let total = res.data[emoType[i]].up + res.data[emoType[i]].mid + res.data[emoType[i]].down;
							if(res.data[emoType[i]].up){
								// this[this.checkType+'PercentAll'][emoType[i]]
								let name = "";
								let color = "#ff4d31";
								if(emoType[i] == 'emotion'){
									name = "心情愉悦";
									color = '#14b3f8'
								}
								if(emoType[i] == 'stress'){
									name = "压力较大";
								}
								if(emoType[i] == 'tired'){
									name = "疲惫";
								}
								piearr.push({
									total,
									value: res.data[emoType[i]].up,
									name: name,
									vlatype:'hig',
									itemStyle: {
										color: color
									}
								})
							}
							if(res.data[emoType[i]].mid){
								// this[this.checkType+'PercentAll'][emoType[i]]
								let name = "";
								let color = "#fcc856";
								if(emoType[i] == 'emotion'){
									name = "心情一般";
								}
								if(emoType[i] == 'stress'){
									name = "中等压力";
								}
								if(emoType[i] == 'tired'){
									name = "精力一般";
								}
								piearr.push({
									total,
									value: res.data[emoType[i]].mid,
									name: name,
									vlatype:'hig',
									itemStyle: {
										color: color
									}
								})
							}
							if(res.data[emoType[i]].down){
								// this[this.checkType+'PercentAll'][emoType[i]]
								let name = "";
								let color = "#ff4d31";
								if(emoType[i] == 'emotion'){
									name = "心情较差";
								}
								if(emoType[i] == 'stress'){
									name = "放松";
									color = "#14b3f8";
								}
								if(emoType[i] == 'tired'){
									color = "#14b3f8";
									name = "精力充沛";
								}
								piearr.push({
									total,
									value: res.data[emoType[i]].down,
									name: name,
									vlatype:'hig',
									itemStyle: {
										color: color
									}
								})
							}
							this[this.checkType+'PercentAll'][emoType[i]] = piearr;
						}
						
						
						this.setDayContent(this.today,this[this.checkType+'PercentAll'][this.indexType]);
						this.percentageChartDay(this[this.checkType+'PercentAll'][this.indexType]);
						let data = this[this.checkType]
						// this.initChartBar(data,'hour')
						if(res.data.affectList.length){
							this.haswordCloud = true;
							let wcdata = toTotalArr(res.data.affectList)
							this.initWordCloud(wcdata);
						}
						
					}
				});
			},
			setWeekContent(data,pie){
				this.weekContent = '';
				let pe = 0;
				let pstr = pie[0].name+'的次数出现最多,';
				if(pie.length){
					for(let i in pie){
						let apie = Math.round(pie[i].value/pie[i].total*100)
						let diff = toDiff(data.data[pie[i].vlatype],data.predata[pie[i].vlatype])
						if(i==0){
							pstr += '占比达到了'+apie+'%，相比上星期'+diff.resStr+'。';
							continue;
						} 
						pstr+=pie[i].name+'占比'+apie+'%,相比上星期'+ diff.resStr+'。';
						switch (this.indexType+'_'+pie[i].vlatype+'_'+diff.res){
							case 'emotion_min_up':
								pstr+=pie[i].name+'的比例增加了，是不是遇到了不开心的事情。'
								break;
							case 'tired_min_up':
								pstr+=pie[i].name+'的比例增加了，相比之前更加精力满满。'
								break;
							case 'stress_min_up':
								pstr+=pie[i].name+'的比例增加了，相比之前更加感觉轻松。'
								break;
							case 'emotion_hig_dn':
								pstr+=pie[i].name+'的比例增加了，心情有所下降。'
								break;
							case 'tired_hig_dn':
								pstr+=pie[i].name+'的比例增加了，更加疲劳。'
								break;
							case 'stress_hig_dn':
								pstr+=pie[i].name+'的比例增加了，感到的压力增加。'
								break;
							default:
								if(diff.res == '=') pstr+='较为平稳。'
							break;
						}
					}
					this.weekContent = pstr;
				}
			},
			setDayContent(data,pie){
				this.dayContent = "";
				this.bestEmoStr = '-';
				this.badEmoStr = '-';
				let strUp = []
				let strDn = []
				for(let i in data){
					if(data[i][this.indexType]){
						if(this.indexType=='emotion'){
							if(data[i][this.indexType]<50){
								strDn.push(data[i].hour)
							}
							if(data[i][this.indexType]>69){
								strUp.push(data[i].hour)
							}
						}else{
							if(data[i][this.indexType]<50){
								strUp.push(data[i].hour)
							}
							if(data[i][this.indexType]>69){
								strDn.push(data[i].hour)
							}
						}
					}
				}
				if(strUp.length){
					let ar = maxsequence(strUp)||[]
					if(ar.length) this.bestEmoStr = ar.join('-') + "时";
				}
				if(strDn.length){
					let br = maxsequence(strDn)||[];
					if(br.length) this.badEmoStr = br.join('-') + "时";
				}
				let strs = ''
				if(pie.length){
					for(let i in pie){
						let pe = (pie[i].value/pie[i].total*100).toFixed(1)*10/10;
						strs += "，" + pie[i].name + pe + "%"
					}
					this.dayContent = "据后台数据显示"+strs+"。";
				}
			},
			//渲染周数据
			initChartBar(initdata,field) {
				let colors = ['#ff4d31', '#fcc856', '#14b3f8'];
				if (this.indexType == "stress") {
					colors = ['#14b3f8', '#fcc856', '#ff4d31'];
				}
				let data = [];
				let time = [];
				for (let i in initdata) {
					if (initdata[i][this.indexType] == -1) continue;
					let item = {value:initdata[i][this.indexType],itemStyle:{color:'#14b3f8'}};
					// if (initdata[i][this.indexType] < 50) {
					// 	item.itemStyle.color = colors[0]
					// } else if (initdata[i][this.indexType] < 70) {
					// 	item.itemStyle.color = colors[1]
					// } else {
					// 	item.itemStyle.color = colors[2]
					// }
					
					data.push(item)
					time.push(initdata[i][field])
				}
				
				let option = {
					legend:{
						show:false
					},
					label:{
						show:false
					},
					xAxis: [{
						axisTick: {
							show: false
						},
						axisLine: {
							show: false
						},
						axisLabel: {
							color: '#A0A4AA'
						},
						type: 'category',
						data: time
					}],
					yAxis: {
							splitLine: {
								show: true,
								lineStyle:{
									type: [5, 10],
									dashOffset: 5,
									color:'#ccc',
								}
							},
							max: 100,
							min: 0,
							type: 'value',
							minInterval: 1,
							interval: 25,
							axisLabel: {
								fontSize: 10,
								formatter: function(value, idx) {
									return value;
								}
							},
						},
					series: [{
						name: 'his',
						type: 'bar',
						data: data,
						barMaxWidth: 7,
						itemStyle: {
							borderRadius: [3, 3, 0, 0],
						},
				
					}]
				};
				this.$nextTick(()=>{
					this.$refs.emoChartBar.init(echarts, chart => {
						chart.setOption(option);
					});
				})
			},
			percentageChartMonth(data,hourdata){
				this.monthContents = ['','',''];
				this.monthHourMean={
					mean:'',
					premean:'',
					diff:''
				}
				let best = 0;
				let low = 0;
				for(let i in this.month){
					if(!this.month[i][this.indexType]) continue;
					if(this.indexType == 'emotion' || this.indexType == 'tired'){
						if(this.month[i][this.indexType]>69){
							best+=1;
						}
						if(this.month[i][this.indexType]<50){
							low+=1;
						}
					}
					if(this.indexType == 'stress'){
						if(this.month[i][this.indexType]>69){
							low+=1;
						}
						if(this.month[i][this.indexType]<50){
							best+=1;
						}
					}
				}
				this.monthContents[1] = best;
				this.monthContents[2] = low;
				let colorList = ['#14b3f8', '#fcc856', '#ff4d31']
				if (this.indexType == "emotion" || this.indexType == 'tired') {
					colorList = ['#ff4d31', '#fcc856', '#14b3f8']
				}
				if (data.length < 1) {
					colorList = ['#ccc', '#ccc', '#ccc']
				}

				this.monthContents[0] = data[0].name;
				this.monthHourMean.mean = hourdata.data.mean;
				this.monthHourMean.premean = hourdata.predata.mean;
				this.monthHourMean.diff = toDiff(hourdata.data.mean,hourdata.predata.mean).resStr||'';

				this.$nextTick(() => {
					if (!this.$refs.emoChartPieMonth) return;
					this.$refs.emoChartPieMonth.init(echarts, chart => {
						let option = {
							series: [{
								percentPrecision:0,
								type: 'pie',
								radius: ['40%', '70%'],
								fontSize:7,
								label: {
									show: true,
									position:"inside",
									formatter: ' {d}%',
									
								},
								avoidLabelOverlap: false,
								labelLine: {
									show: false
								},
								data: data,

							}]
						};
						chart.setOption(option);
					});
				})
			},
			//渲染情绪扇形状图
			percentageChartDay(data) {
				// console.log(data);
				let colorList = ['#14b3f8', '#fcc856', '#ff4d31']
				// if (this.indexType == "tired" || this.indexType == "emotion") {
				if (this.indexType == "tired") {
					colorList = ['#ff4d31', '#fcc856', '#14b3f8']
				}
				if (data.length < 1) {
					colorList = ['#ccc', '#ccc', '#ccc']
				}
				this.$nextTick(() => {
					if (!this.$refs.emoChartPie) return;
					this.$refs.emoChartPie.init(echarts, chart => {
						let option = {
							series: [{
								percentPrecision:1,
								type: 'pie',
								radius: ['40%', '70%'],
								avoidLabelOverlap: false,
								labelLine: {
									show: false
								},
								data: data,
								label: {
									alignTo: 'edge',
									formatter: '{name|{b}}\n{time|{d} %}',
									minMargin: 5,
									edgeDistance: 10,
									lineHeight: 15,
									rich: {
										time: {
											fontSize: 10,
											color: '#999'
										}
									}
								},
								labelLine: {
									length: 15,
									length2: 0,
									maxSurfaceAngle: 80
								},
								labelLayout: function(params) {
									const isLeft = params.labelRect.x < chart.getWidth() /
										2;
									const points = params.labelLinePoints;
									points[2][0] = isLeft ?
										params.labelRect.x :
										params.labelRect.x + params.labelRect.width;
									return {
										labelLinePoints: points
									};
								},
							}]
						};
						chart.setOption(option);
					});
				})
			},
			dataDay() {
				uni.$u.http.post('/client/data_day', {
					phone: this.member.phone,
				}).then(res => {
					if (res.status == 200) {
						this.allMonthData = res.data.allMonthData
					}
				});
			},
			initWordCloud(data) {
				this.$refs.chartRef.init(echarts, chart => {
					chart.setOption({
						series: [{
							type: 'wordCloud',
							wait: 100,
							shape: 'circle',
							left: '0',
							top: '0',
							sizeRange: [12, 60],
							rotationRange: [-90, 90],
							rotationStep: 45,
							gridSize: 8,
							drawOutOfBound: true,
							layoutAnimation: true,
							textStyle: {
								fontFamily: 'sans-serif',
								fontWeight: 'bold',
								color: function() {
									return 'rgb(' + [
										Math.round(Math.random() * 160),
										Math.round(Math.random() * 160),
										Math.round(Math.random() * 160)
									].join(',') + ')';
								}
							},
							emphasis: {
								focus: 'self',
								textStyle: {
									shadowBlur: 10,
									shadowColor: '#333'
								}
							},
							data
						}]
					});
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tabs {
		width: 490rpx;
		background: rgba(29, 110, 250, 0.1);
		text-align: center;
		line-height: 58rpx;
		display: flex;
		border-radius: 29rpx;
	}

	.tabs-item {
		width: 150rpx;
		height: 58rpx;
		margin: 6rpx 0 6rpx 10rpx;
	}

	.activeItem {
		border-radius: 29rpx;
		background: #ffffff;
	}

	.emo-type {
		z-index: 9999;
		color: #3f3d3e;
		width: 130rpx;
		height: 48rpx;
		font-size: 22rpx;
		line-height: 48rpx;
		border-radius: 22rpx;
		box-sizing: border-box;
		margin: 0 auto;
		// background: #ffffff;
		text-align: center;
	}

	.emo-type-item {
		border: 1rpx solid #1d6efa80;
		background-color: #fff;
		margin-bottom: 15rpx;
		width: 130rpx;
		height: 48rpx;
		line-height: 48rpx;
		border-radius: 22rpx;
	}
	.data-day-modal {
		position: fixed;
		height: 100vh;
		width: 100%;
		left: 0px;
		bottom: 0px;
		background-color: rgba(0, 0, 0, 0.3);
		z-index: 100;
	}
	
	.data-day {
		position: relative;
		background-color: #fff;
		border-radius: 15px 15px 0px 0px;
		height: 75vh;
		margin-top: 25vh;
		overflow-y: auto;
	}
	.litteA{
		width: 325px;height: 6px;display:flex;font-size: 9px;
		justify-content: space-around;
	}
	.litteB{
		width:5.4px;
		height:2px;
		border-radius: 1px;
		background:#e5e5e5;
		justify-content: space-around;
	}
	.close {
		display: block;
		width: 30px;
		height: 30px;
		margin: 0px auto;
	}
	.pie-box{
		margin: 10rpx auto;
	}
	.pie-title{
		color: #333333;
		font-size: 12px;
		font-weight: 500;
	}
	.pie-content{
		color: #b0acac;
		font-size: 9px;
	}
	.date-select{
		color: #1D6EFA;font-size: 25rpx;text-align: center;display: flex;justify-content: center;font-weight: 700;
	}
	.day-month {
		padding: 5px 32px;
		margin: 5px 0px;
	}
	.emoTimeItem{
		width: 15px;display:flex;font-size: 9px;flex-direction: column;height: 198px;justify-content: space-between;text-align: center;
	}
	.month-title {
		height: 20px;
		line-height: 20px;
		margin-bottom: 10px;
		font-size: 16px;
		color: #333;
		font-weight: bolder;
		text-align: center;
	}
	
	.day-list {
		display: flex;
		justify-content: flex-start;
		flex-wrap: wrap;
	}
	.day-box {
		width: 14.2%;
		height: 20px;
	}
	.day {
		display: block;
		border: none;
		height: 20px;
		width: 20px;
		margin: 0 auto;
		line-height: 20px;
		text-align: center;
		font-size: 12px;
		color: #666;
		background-color: #fff;
		padding: 0px;
	}
	.day-ac {
		display: block;
		border: none;
		height: 20px;
		width: 20px;
		margin: 0 auto;
		line-height: 20px;
		text-align: center;
		font-size: 12px;
		color: #fff;
		background-color: #01D6D6;
		border-radius: 50%;
		padding: 0px;
	}
	.b-image{
		margin: 20rpx 10rpx;
		width: 110rpx;
		height: 110rpx;
	}
	.b-title{
		font-size: 27.2rpx;
		font-weight: 600;
		color: #2f3033;
		margin: 0 10rpx;
	}
	.b-btn{
		text-align: center;
		color: #fff;
		  width: 108rpx;
		  height: 30rpx;
		  margin: 20rpx 10rpx;
		  border-radius: 25.2rpx;
		  font-size: 17.8rpx;
		  background: #14b3f7;
	}
	.m-box{
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 40rpx;
	}
	.m-b-item{
		width: 130rpx;
	}
	.mb-title{
		text-align: center;
		color: #777777;
		font-size: 22rpx;
	}
	.mb-content{
		margin-top: 10rpx;
		text-align: center;
		color: #333333;
		font-size: 34rpx;
		font-weight: bold;
	}
</style>